package net.controller;


import net.common.ServiceResponse;
import net.pojo.Category;
import net.pojo.Product;
import net.pojo.ProductVo;
import net.service.CategoryService;
import net.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Product> list = productService.findAll();
        List<Category> list1 = categoryService.findAll();
        model.addAttribute("list",list);
        model.addAttribute("c",list1);
        return "/admin/products/list.jsp";
    }

    @RequestMapping("/searchProduct")
    @ResponseBody
    public List<Product> searchProduct(ProductVo productVo){
        List<Product> list = productService.search(productVo);
        return list;
    }

    @RequestMapping("/addProduct")
    @ResponseBody
    public ServiceResponse addProduct( Product product,@RequestParam(required = false,value = "prfie") MultipartFile file, HttpServletRequest request){
        ServiceResponse serviceResponse = productService.addProduct(product,file,request);
        return serviceResponse;
    }

    @RequestMapping("/addUI")
    public String addUI(Model model,Category category){
        List<Category> list = categoryService.findAll();
        model.addAttribute("list",list);
        return "/admin/products/add.jsp";
    }

    @RequestMapping("/deleteById")
    public String deleteById(String id){
        int i = productService.deleteById(id);
        return "redirect:/product/findAll.do";
    }

    @RequestMapping("/updateProduct")
    @ResponseBody
    public ServiceResponse updateProduct(Product product){
        ServiceResponse serviceResponse = productService.updateProduct(product);
        return serviceResponse;
    }

    @RequestMapping("/editUI")
    public String editUI (String id,Model model){
        Product product = productService.findById(id);
        List<Category> list1 = categoryService.findAll();
        model.addAttribute("product",product);
        model.addAttribute("c",list1);
        return "/admin/products/edit.jsp";
    }

}

